const { importSchema } = require('graphql-import')
const { mergeSchemas } = require('graphql-tools')

const fetchRemoteSchema = require('./fetchRemoteSchema')
const Mutation = require('../resolvers/Mutation')
const MergeMutation = require('../resolvers/MergeMutation')
const ExtendUser = require('../resolvers/ExtendUser')
const ExtendRole = require('../resolvers/ExtendRole')

const { getTypeFields } = require('../utils')

const mergedSchema = async redis => {
  const userSchema = await fetchRemoteSchema('http://localhost:4001')
  redis.set(
    'userSchema_queryType_fields',
    getTypeFields(userSchema['_queryType'])
  )
  redis.set(
    'userSchema_mutationType_fields',
    getTypeFields(userSchema['_mutationType'])
  )
  const roleSchema = await fetchRemoteSchema('http://localhost:4002')
  redis.set(
    'roleSchema_queryType_fields',
    getTypeFields(roleSchema['_queryType'])
  )
  redis.set(
    'roleSchema_mutationType_fields',
    getTypeFields(roleSchema['_mutationType'])
  )
  const menuSchema = await fetchRemoteSchema('http://localhost:4003')
  redis.set(
    'menuSchema_queryType_fields',
    getTypeFields(menuSchema['_queryType'])
  )
  redis.set(
    'menuSchema_mutationType_fields',
    getTypeFields(menuSchema['_mutationType'])
  )
  const organizationSchema = await fetchRemoteSchema('http://localhost:4004')
  redis.set(
    'organizationSchema_queryType_fields',
    getTypeFields(organizationSchema['_queryType'])
  )
  redis.set(
    'organizationSchema_mutationType_fields',
    getTypeFields(organizationSchema['_mutationType'])
  )
  // console.log(userSchema, roleSchema)
  const authTypeDefs = importSchema(`${__dirname}/authTypeDefs.graphql`)
  const userLinkTypeDefs = `
  extend type PriUser {
    roles: RoleConnection
    organizations: OrganizationConnection
  }  
  `
  const roleLinkTypeDefs = `
  extend type Role {
    menus: MenuConnection
  }  
  `
  // console.log(authTypeDefs, userLinkTypeDefs)
  // 更新 redis 权限列表
  // console.log(userSchema)
  /* for (let i in userSchema['_queryType']) {
    console.log(i, '===', userSchema['_queryType'][i])
  }
  for (let i in userSchema['_mutationType']) {
    console.log(i, '===', userSchema['_mutationType'][i])
  } */
  return mergeSchemas({
    schemas: [
      userSchema,
      roleSchema,
      menuSchema,
      organizationSchema,
      authTypeDefs,
      userLinkTypeDefs,
      roleLinkTypeDefs
    ],
    resolvers: {
      Mutation: {
        ...Mutation,
        ...MergeMutation({ userSchema })
      },
      ...ExtendUser({ roleSchema, organizationSchema }),
      ...ExtendRole({ menuSchema })
    }
  })
}

module.exports = mergedSchema
